package com.wejoy.video.middle.station.api.controller.user;

import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.api.annotation.LoginCheck;
import com.wejoy.video.middle.station.data.domain.system.*;
import com.wejoy.video.middle.station.data.enums.dict.EnumOrderRoleType;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.common.IVerifyCodeService;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.service.system.ISysRoleOrderService;
import com.wejoy.video.middle.station.data.service.system.ISysRoleResourceService;
import com.wejoy.video.middle.station.data.service.system.ISysRoleService;
import com.wejoy.video.middle.station.data.service.system.ISysUserService;
import com.wejoy.video.middle.station.data.util.ConstantValues;
import com.wejoy.video.middle.station.data.util.LoginUtil;
import com.wejoy.video.middle.station.data.util.RSAUtil;
import com.wejoy.video.middle.station.data.util.baiduevs.EvsApiHttpUtils;
import com.wejoy.video.middle.station.data.util.user.SysUserLoginUtil;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.evsapi.DeparmentInfoListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author miracle_j
 * Create by 2024/3/28 11:30 AM
 */
@RestController
@RequestMapping("/user")
public class UserAction {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IEvsHttpService evsHttpService;
    @Autowired
    private ISysRoleOrderService sysRoleOrderService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysRoleResourceService roleResourceService;

    /**
     * 生成验证码图片与存入SESSION
     *
     * @param response
     * @param webSession
     * @return
     * @throws IOException
     */
    @ResponseBody
    @GetMapping("/verifyCode")
    public RespJSON verifyCode(HttpServletResponse response, HttpSession webSession) throws IOException {
        JSONObject verificationCode = EvsApiHttpUtils.getVerificationCode();
        return RespJSON.success(verificationCode);
    }

    /**
     * 登陆
     * <p>
     * param username 用户名
     * param password 密码
     *
     * @return
     */
    @PostMapping("/login")
    public RespJSON login(@RequestBody SysUser sysUser, HttpServletRequest request) {
//        try {
//            sysUser.setPassword(RSAUtil.decrypt(sysUser.getPassword(),RSAUtil.private_key));
//        } catch (Exception e) {
//            throw new BusinessException("非法参数");
//        }
        SysUser sysUserDB = sysUserService.login(sysUser);
        userInfo(sysUserDB,request);
        LoginUtil.saveInCache(sysUserDB, request);
        return RespJSON.success(sysUserDB.getToken());
    }

    @GetMapping("/getCurrentUser")
    @LoginCheck
    public RespJSON getCurrentUser(@SessionAttribute(value = LoginUtil.LOGIN_USER_SESSION_KEY) SysUser loginSysUser,HttpServletRequest request) {
        List<SysRole> currentUserRole = sysRoleService.getCurrentUserRole(loginSysUser);
        loginSysUser.setSysRoleList(currentUserRole);
        List<String> sysResourceIdentityList = new ArrayList<>();
        List<SysResource> sysResourceList = new ArrayList<>();
        roleResourceService.buildUserResourceListAndIdentityList(currentUserRole, sysResourceList, sysResourceIdentityList);
        if (CollectionUtils.isEmpty(currentUserRole)) {
            currentUserRole = new ArrayList<>();
            SysRole sysRole = new SysRole();
            sysRole.setName("首页");
            currentUserRole.add(sysRole);
            loginSysUser.setSysRoleList(currentUserRole);
        }
        //查询用户默认工单权限部门
        List<Long> deptIds = getDeptIds(loginSysUser);
        if(CollectionUtils.isEmpty(deptIds)){
            //项目管理员
            if(loginSysUser.getType().equals("project_admin")){
                deptIds.add(EnumOrderRoleType.ALL_ROLE.getCode().longValue());
                loginSysUser.setDataPermissionDeptIds(deptIds);
            }
            //普通用户默认查询本部门工单，不包含子部门
            if(loginSysUser.getType().equals("ordinary_user")){
                List<Long> collect = loginSysUser.getDepartmentInfoList().stream()
                        .map(DeparmentInfoListVO::getDepartmentId) // 提取每个SysRoleOrder对象的id属性
                        .collect(Collectors.toList());
                loginSysUser.setDataPermissionDeptIds(collect);
            }
        }else {
            loginSysUser.setDataPermissionDeptIds(deptIds);
        }
        loginSysUser.setSysResourceList(sysResourceList);
        loginSysUser.setSysResourceIdentityList(sysResourceIdentityList);
        LoginUtil.refreshCache(loginSysUser,request);
        return RespJSON.success(loginSysUser);
    }

    private void userInfo(SysUser loginSysUser,HttpServletRequest request){
        List<SysRole> currentUserRole = sysRoleService.getCurrentUserRole(loginSysUser);
        loginSysUser.setSysRoleList(currentUserRole);
        List<String> sysResourceIdentityList = new ArrayList<>();
        List<SysResource> sysResourceList = new ArrayList<>();
        roleResourceService.buildUserResourceListAndIdentityList(currentUserRole, sysResourceList, sysResourceIdentityList);
        if (CollectionUtils.isEmpty(currentUserRole)) {
            currentUserRole = new ArrayList<>();
            SysRole sysRole = new SysRole();
            sysRole.setName("首页");
            currentUserRole.add(sysRole);
            loginSysUser.setSysRoleList(currentUserRole);
        }
        //查询用户默认工单权限部门
        List<Long> deptIds = getDeptIds(loginSysUser);
        if(CollectionUtils.isEmpty(deptIds)){
            //项目管理员
            if(loginSysUser.getType().equals("project_admin")){
                deptIds.add(EnumOrderRoleType.ALL_ROLE.getCode().longValue());
                loginSysUser.setDataPermissionDeptIds(deptIds);
            }
            //普通用户默认查询本部门工单，不包含子部门
            if(loginSysUser.getType().equals("ordinary_user")){
                List<Long> collect = loginSysUser.getDepartmentInfoList().stream()
                        .map(DeparmentInfoListVO::getDepartmentId) // 提取每个SysRoleOrder对象的id属性
                        .collect(Collectors.toList());
                loginSysUser.setDataPermissionDeptIds(collect);
            }
        }else {
            loginSysUser.setDataPermissionDeptIds(deptIds);
        }
        loginSysUser.setSysResourceList(sysResourceList);
        loginSysUser.setSysResourceIdentityList(sysResourceIdentityList);
    }


    private List<Long> getDeptIds(SysUser loginSysUser){
        List<Long> ids = new ArrayList<>();
        SysRoleOrder sysRoleOrder = new SysRoleOrder();
        sysRoleOrder.setUserId(loginSysUser.getId());
        List<SysRoleOrder> list = sysRoleOrderService.getList(sysRoleOrder);
        if(CollectionUtils.isEmpty(list)){
            return ids;
        }
        //自定义部门
        ids=list.stream()
                .map(SysRoleOrder::getDeptId) // 提取每个SysRoleOrder对象的id属性
                .collect(Collectors.toList()); // 收集到新的ArrayList中
        if(list.size()==1){
            SysRoleOrder roleOrder = list.get(0);
            //本部门
            if(roleOrder.getDeptId() == 0){
                if(CollectionUtils.isEmpty(loginSysUser.getDepartmentInfoList())){
                    return ids;
                }
                ids = loginSysUser.getDepartmentInfoList().stream()
                        .map(DeparmentInfoListVO::getDepartmentId) // 提取每个SysRoleOrder对象的id属性
                        .collect(Collectors.toList());// 收集到新的ArrayList中
                return ids;
            }
            if(roleOrder.getDeptId() == 1){
                if(CollectionUtils.isEmpty(loginSysUser.getDepartmentInfoList())){
                    return ids;
                }
                List<Long> finanList = new ArrayList<>();
                loginSysUser.getDepartmentInfoList().forEach(item->{
                    getIds(item.getDepartmentId(),loginSysUser.getToken(), finanList);
                    if (!finanList.contains(item.getDepartmentId())) {
                        finanList.add(item.getDepartmentId());
                    }
                });
                //返回去重后的list
                return finanList.stream().distinct().collect(Collectors.toList());
            }
            if(roleOrder.getDeptId() == 3){
                ids.add(EnumOrderRoleType.ALL_ROLE.getCode().longValue());
                return ids;
            }
            //子部门
            return ids;
        }
        return ids;
    }

    /**
     * 获取子部門的所有id
     */
    private void getIds(Long deptId,String token,List<Long> ids){
        SysDept evsApiDept = new SysDept();
        evsApiDept.setParentId(deptId.intValue());
        evsApiDept.setIncludeLower(true);
        List<SysDept> departments = evsHttpService.getDepartments(evsApiDept, token);
        List<Long> collect = departments.stream()
                .map(SysDept::getId) // 提取每个SysRoleOrder对象的id属性
                .collect(Collectors.toList());// 收集到新的ArrayList中
        ids.addAll(collect);
    }



}
